<?php

namespace App\HttpController\Admin;

use Exception;
use EasySwoole\ORM\DbManager;
use EasySwoole\EasySwoole\Task\TaskManager;


use App\Task\CacheDel;
use App\Common\Tools;
use App\Common\RedisCache;
use App\Common\Cache\CategoryCache;
use App\Model\Article\ {
    Nav,
    Article
};
use App\Common\Traits\Admin\ {
    Lists as AdminList,
    Info as AdminInfo,
    Create as AdminCreate,
    Modify as AdminModify,
    Delete as AdminDelete,
};
use App\Validate\Nav as ValidateNav;
use App\Validate\Delete as ValidateDelete; 

class Category extends Base
{
    use AdminList;
    use AdminInfo;
    use AdminCreate;
    use AdminModify;
    use AdminDelete;

    /**
     * @description: 模型
     * @var Model
     */
    public $model = Nav::class;

    /**
     * @description: 主键
     * @var 
     */
    public $id = 'id';

    /**
     * @description: 列表查询条件构建
     * @param array $param 前端参数
     * @return {*}
     */
    protected function indexWhere(array $param)
    {
        $where = [];
        Tools::conditionQuery($where, $param, 'name', 'name', 'like');
        Tools::conditionQuery($where, $param, 'parent_id', 'parent_id', '=');
        Tools::conditionQuery($where, $param, 'display', 'display', '=');
        return $where;
    }

    /**
     * @description: 列表数据额外返回数据
     * @param {*}
     * @return {*}
     */
    protected function indexAssign()
    {
        return ['navs' => $this->getNavTree()];
        
    }

    /**
     * @description: 列表查询条件默认字段
     * @param {*}
     * @return {*}
     */
    protected function indexDeafultParam()
    {
        return [
            'name'      => '',
            'parent_id' => '',
            'display'   => '',
        ];
    }

    /**
     * @description: 单条数据查询额外返回数据
     * @param {*}
     * @return {*}
     */
    protected function infoAssign()
    {
        return ['navs' => $this->getNavTree()];
        
    }

    /**
     * @description: 获取文章分类树
     * @param {*}
     * @return {*}
     */
    public function getNavTree()
    {
        return DbManager::getInstance()->invoke(function ($client) {
            $model = Nav::invoke($client);
            $data  = $model->scopWhere()->all()->toArray();
            return Tools::recursiveTree($data);
        });
    }

    /**
     * @description: 验证创建参数
     * @param array $param 前端参数
     * @return {*}
     */
    protected function validateCreate(array $param)
    {
        return (new ValidateNav)->validate($param);
    }

    /**
     * @description: 创建后
     * @param array $param 前端参数
     * @return {*}
     */
    protected function afterCreate(array $param)
    {
        $task = TaskManager::getInstance();
        $args = [
            'func'  => 'afterCreate',
            'param' => $param
        ];
        $call = ['call' => [new CategoryCache, 'del'], 'args' => $args];
        $task->async(new CacheDel($call));
        return true;
    }

    /**
     * @description: 修改显示属性
     * @param array $param 前端参数
     * @return {*}
     */
    protected function afterMofidyDisplay(array $param)
    {
        $task = TaskManager::getInstance();
        $args = [
            'func'  => 'afterMofidyDisplay',
            'param' => $param
        ];
        $call = ['call' => [new CategoryCache, 'del'], 'args' => $args];
        $task->async(new CacheDel($call));

        $nav = DbManager::getInstance()->invoke(function ($client) use ($param) {
            $model = Nav::invoke($client);
            return $model->get($param['id'])->toArray();
        });
        $keys = [
            'nav:' . $param['id'] . ':child', 
            'nav:' . $param['id'] . ':level', 
        ];
        if ($nav['is_show'] == 1) {
            $keys[] = 'nav:home';
            $keys[] = 'article:home';
        }
        $pkeys = RedisCache::keys('nav:' . $param['id'] . ':page:*');
        $keys  = array_merge($keys, $pkeys);
        RedisCache::del($keys);
        return true;
    }

    /**
     * @description: 验证删除参数
     * @param array $param 前端参数
     * @return {*}
     */
    protected function validDelete(array $param)
    {
        $errMsg = (new ValidateDelete)->validate($param);
        if ($errMsg !== true) {
            return $errMsg;
        }
        $errMsg = DbManager::getInstance()->invoke(function ($client) use ($param) {
            $navModel   = Nav::invoke($client);
            $artModel   = Article::invoke($client);
            $ids        = explode(',', $param['id']);
            $navs_id = $artModel->where('navs_id', $ids, 'in')
                        ->group('navs_id')->column('navs_id');
            if ($navs_id) {
                $names = $navModel->where('id', $navs_id, 'in')->column('name');
                return '分类' . implode(',', $names) . '下还有文章，不能删除';
            } else {
                return true;
            }
        });

        return $errMsg;
    }

    /**
     * @description: 删除前
     * @param array $param 前端参数
     * @return {*}
     */
    protected function beforeDelete(array $param)
    {
        $task = TaskManager::getInstance();
        $args = [
            'func'  => 'beforeDelete',
            'param' => $param
        ];
        $call = ['call' => [new CategoryCache, 'del'], 'args' => $args];
        $task->sync(new CacheDel($call));
        return true;
    }
}
